package org.spiderflow.ocr.executor.shape;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.spiderflow.ExpressionEngine;
import org.spiderflow.context.SpiderContext;
import org.spiderflow.executor.ShapeExecutor;
import org.spiderflow.model.Shape;
import org.spiderflow.model.SpiderNode;
import org.spiderflow.ocr.model.Ocr;
import org.spiderflow.ocr.utils.OcrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class OcrOperationExecutor implements ShapeExecutor{
	
	public static final String OCR_ID = "ocrId";
	
	public static final String BYTES_OR_URL = "bytesOrUrl";
	
	public static final String VARIABLE_NAME = "variableName";
	
	@Autowired
	private ExpressionEngine engine;
	
	@Override
	public String supportShape() {
		return "ocrOperation";
	}
	
	@Override
	public Shape shape() {
		Shape shape = new Shape();
		shape.setImage("");
		shape.setLabel("OCR识别");
		shape.setName("ocrOperation");
		shape.setTitle("OCR识别");
		return shape;
	}

	@Override
	public void execute(SpiderNode node, SpiderContext context, Map<String, Object> variables) {
		String ocrId = node.getStringJsonValue(OCR_ID);
		Ocr ocr = (Ocr) context.get(OcrExecutor.OCR_CONTEXT_KEY + ocrId);
		if(!StringUtils.isNotBlank(ocrId)){
			context.debug("请选择OCR！");
		}else {
			String bytesOrUrl = node.getStringJsonValue(BYTES_OR_URL);
			JSONObject jsonResult = null;
			if(bytesOrUrl.startsWith("http")) {
				jsonResult = OcrUtil.ocrIdentify(ocr, bytesOrUrl);
			}else {
				byte[] bytes = (byte[]) engine.execute(bytesOrUrl, variables);
				jsonResult = OcrUtil.ocrIdentify(ocr, bytes);
			}
			if(jsonResult != null) {
				JSONArray wordsResult = jsonResult.getJSONArray("words_result");
				if(wordsResult != null) {
					double average = 0;
					String identifyResult = "";
					for (int i = 0; i < wordsResult.length(); i++) {
						JSONObject probability = wordsResult.getJSONObject(i).getJSONObject("probability");
						if(probability.getDouble("average") > average) {
							average = probability.getDouble("average");
							identifyResult = wordsResult.getJSONObject(i).getString("words");
						}
					}
					variables.put(node.getStringJsonValue(VARIABLE_NAME),identifyResult);
				}
			}
		}
	}
	
}